package com.voice.call.filter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.voice.call.common.Result;
import com.voice.call.utils.AESEncryptUtil;
import com.voice.call.utils.JSONUtil;

@ControllerAdvice
public class LocalResponseBodyAdvice implements ResponseBodyAdvice<Object>{
	
	//白名单
    private static List<String> signWhiteList = Collections.synchronizedList(new ArrayList<String>());
    
    //private final Logger log = LoggerFactory.getLogger(LocalResponseBodyAdvice.class);
	
	@PostConstruct
	public void init() throws Exception {
		
		signWhiteList.add("clearSystemConfig");//清除缓存
		signWhiteList.add("clearVosConfig");//清除缓存
		signWhiteList.add("testUpdLocal");//清除缓存
		
		signWhiteList.add("feedbackSuggestion");//意见反馈
		signWhiteList.add("smsReceived");//短信回调
		signWhiteList.add("uploadFileList");//上传文件
	
		signWhiteList.add("createVosAccount");//vos创建
		signWhiteList.add("deleteVosAccount");//vos创建
		signWhiteList.add("queryVosAccount");//vos创建
		
	}

	 @Override
	 public Object  beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			 @SuppressWarnings("rawtypes") Class clas,ServerHttpRequest request, ServerHttpResponse response){
		 
		 
		 Result rs = (Result)body;
		 if (rs!=null) {

			 String jsonStr = JSONUtil.objectToJson(rs);
			 String respTxt = AESEncryptUtil.encrypt(jsonStr, AESEncryptUtil.APP_KEY);
			 //log.info("respTxt = {}",respTxt);
			 return respTxt;
			 
		 }
		 return body;
		 
	 }
	

	@Override
    public boolean supports(MethodParameter methodParameter, @SuppressWarnings("rawtypes") Class clas) {
		String methodName=methodParameter.getMethod().getName(); 
		 System.out.print("methodName url="+methodName);
		 
		 if (signWhiteList.contains(methodName)) { //不拦截
			 System.out.print("返回不加密");
			 return false;
		 }
		 
		return methodParameter.getMethod().getReturnType().isAssignableFrom(Result.class);
		
		//或者直接返回 return true;
    }
	
}
